#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024-6-3 9:06
# @Author  : jiaoxianzhong
# @File    : log_handler.py.py
# @Software: PyCharm
import os
import logging
import re
import time
from logging.handlers import RotatingFileHandler, TimedRotatingFileHandler


class LogHandler(object):
    # log配置，实现日志自动按日期生成日志文件

    @classmethod
    def make_dir(cls, make_dir_path):
        path = make_dir_path.strip()
        if not os.path.exists(path):
            os.makedirs(path)

    @classmethod
    def get_log_handlers(cls):
        handler_list = [cls.create_loglevel_handler(logging.INFO), cls.create_loglevel_handler(logging.WARNING),
                        cls.create_loglevel_handler(logging.ERROR)]
        return handler_list

    @classmethod
    def create_loglevel_handler(cls, level):
        # 日志级别名称
        lever_name = logging.getLevelName(level).lower()
        # 日志路径地址
        log_dir_name = "logs"
        # 文件名，以日期作为文件名
        log_file_name = time.strftime('%Y-%m-%d', time.localtime(time.time())) + lever_name + '.log'
        # 创建日志文件夹
        log_folder = os.path.abspath(
            os.path.join(os.path.dirname(__file__), os.pardir, log_dir_name, lever_name))
        cls.make_dir(log_folder)
        # 完整日志文件路径
        log_full_path = os.path.join(log_folder, log_file_name)
        # 默认日志等级的设置
        logging.basicConfig(level=logging.INFO)
        # 创建日志记录器，指明日志保存路径,每个日志的大小，保存日志的上限
        # info_handler = TimedRotatingFileHandler(os.path.join(info_log_folder, 'info.log'), when='midnight')
        handler = RotatingFileHandler(log_full_path, maxBytes=1024 * 1024, backupCount=7, encoding='UTF-8')
        # 设置日志的格式                   发生时间    日志等级     日志信息文件名      函数名          行数        日志信息
        formatter = logging.Formatter(
            '%(asctime)s - %(levelname)s - %(filename)s - %(funcName)s - %(lineno)s - %(message)s')
        # 将日志记录器指定日志的格式
        handler.setFormatter(formatter)
        # 过滤器来过滤掉其他级别的日志
        handler.addFilter(lambda record: record.levelno == level)
        # 日志等级的设置
        # handler.setLevel(logging.INFO)
        return handler
